import jieba.analyse
import matplotlib.pyplot as plt
from matplotlib.image import imread
from wordcloud import ImageColorGenerator
from wordcloud import WordCloud
import random
list = ['ecb889', 'ffffff', '1682d6', '78bdb8']
inst = random.randint(0, 3)

back_img = imread(
    "py/"+list[inst]+".jpg")
img_colors = ImageColorGenerator(back_img)

print('执行了呀！！！')

# 编码小说改成gbk
with open("py/log.txt", encoding="utf8") as file:
    jieba.analyse.set_stop_words(
        'py/stopwords.txt')  # 设置止词列表
    tags = jieba.analyse.extract_tags(file.read(), 1000, withWeight=True)
    data = {item[0]: item[1] for item in tags}
    word_cloud = WordCloud(font_path="/usr/share/fonts/Arial Unicode.ttf",
                           background_color="#"+list[inst],
                           max_words=400,
                           max_font_size=100,
                           scale=4,
                           width=500,
                           height=500,
                           mask=back_img,
                           ).generate_from_frequencies(data)

    word_cloud.recolor(color_func=img_colors)  # 替换默认的字体颜色
    plt.figure()  # 创建一个图形实例
    fig = plt.gcf()
    plt.axis('off')
    fig.set_size_inches(500/500, 500/500)
    plt.imshow(word_cloud, interpolation='bilinear')
    plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
    plt.savefig("py/txt.png", format='png', dpi=500, pad_inches=0)
